import { createStore, Store, useStore as vuexUseStore } from "vuex";
import { IRootState } from "./types";
import { App } from "vue";
import loginModule from "./login/login";
import { IStoreType } from "./types";
import systemModule from "./main/system/system";

import { getPageListData } from "@/service/main/system/system";

const store = createStore<IRootState>({
  state() {
    return {
      name: "wang",
      age: 18,
      height: "10",
      entireDepartments: [],
      entireRole: [],
      entireMenu: [],
    };
  },
  getters: {},
  mutations: {
    changeEntireDepartment(state, list) {
      state.entireDepartments = list;
    },
    changeEntireRole(state, list) {
      state.entireRole = list;
    },
    changeEntireMenu(state, list) {
      state.entireMenu = list;
    },
  },
  actions: {
    async getInitialDataAction({ commit }) {
      //  1、请求部门和角色数据
      const departmentResult = await getPageListData("/department/list", {
        offset: 0,
        size: 1000,
      });
      const { list: departmentList } = departmentResult.data;
      const roleResult = await getPageListData("/role/list", {
        offset: 0,
        size: 1000,
      });
      const { list: roleList } = roleResult.data;
      const menuResult = await getPageListData("/menu/list", {});
      const { list: menuList } = menuResult.data;

      // 2、保存数据
      commit("changeEntireDepartment", departmentList);
      commit("changeEntireRole", roleList);
      commit("changeEntireMenu", menuList);
    },
  },
  modules: {
    loginModule,
    systemModule,
  },
});

// 从localStorage里初始化 store
export function setupStore(app: App): void {
  app.use(() => {
    store.dispatch("loginModule/loadLocalLogin");
    // store.dispatch("getInitialDataAction");
  });
}

export function useStore(): Store<IStoreType> {
  return vuexUseStore();
}

export default store;
